<template>
  <div>
    <h2 align="center">用户--投资项目页面</h2>
    <table class="table table-bordered">
      <tr>
        <td align="right">项目名称:</td>
        <td>
          {{ list.I_Name }}
        </td>
      </tr>

      <tr>
        <td align="right">投资总金额:</td>
        <td>
          {{ list.I_Budget }}
        </td>
      </tr>

      <tr>
        <td align="right">已投金额:</td>
        <td>
         {{ list.I_Receive }}
        </td>
      </tr>

      <tr>
        <td align="right">剩余金额:</td>
        <td>
          {{ list.I_Residue }}
        </td>
      </tr>

      <tr>
        <td align="right">投资金额:</td>
        <td>
          <input type="text" v-model="addInvestData.UI_Money">
        </td>
      </tr>

      <tr v-if="addInvestData.UI_Money!=''">
        <td align="right">预期最高收益:</td>
        <td>
          {{ maxMoney }}
        </td>
      </tr>

      <tr>
        <td></td>
        <td>
          <input type="button" value="确认投资" @click="MakeInvest" class="btn btn-primary">
        </td>
      </tr>
    </table>
  </div>
</template>

<script setup lang="ts">

import {reactive,toRefs,onMounted,ref,watch} from 'vue';

import { useRouter,useRoute } from 'vue-router';

import {useUserStore} from '../../store/user'

import axios from 'axios';

let userStore = useUserStore();

//路由
let router = useRouter();
let route = useRoute();


//数据
let data:any =reactive({
  list:{},
   addInvestData:{
    I_Name:'',
    I_Budget:'',
    UI_Money:'',
    U_Id :userStore.userInfo.U_Id,
    I_Id:route.query.I_Id
   },
   maxMoney:'',
})

//解构
let {list,addInvestData,maxMoney} = toRefs(data);

//监听
watch(()=>addInvestData.value.UI_Money,(newVal,oldVel)=>{
  console.log(newVal,oldVel);
  maxMoney.value=(Number(newVal)*0.06).toFixed(2)+'CNF'
})

//生命周期
onMounted(()=>{
  getData()
})

//回显
//反填
const getData = ()=>{
  axios({
    url:'/api/Invest/GetInvestItem',
    method:'get',
    params:{
      I_Id:route.query.I_Id
    }
  }).then(res=>{
    console.log(res);
    list.value=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })
}

//确认投资
const MakeInvest = ()=>{
   //非空判断
   if(addInvestData.value.UI_Money ==''){
    return alert('投资金额不能为空')
   }
   //判断投资金额是否为数字
   if(isNaN(Number(addInvestData.value.UI_Money))==true){
    return alert('投资总金额必须为数字');
   }
   if(addInvestData.value.UI_Money>addInvestData.value.I_Residue){
    return alert('投资金额不能大于剩余投资金额');
   }
   console.log(addInvestData.value);
   
   //发送网络请求
   axios({
      url:'/api/Invest/PostAddUserInvest',
      method:'post',
      data:addInvestData.value
   }).then(res=>{
      console.log(res);
      if(res.data.data==-1){
        return alert('投资金额不能大于剩余投资金额')
      }
       if(res.data.data>0){
         alert('投资成功');
         //跳转用户投资列表
         router.push('/main/userInvestList');
      }else{
         alert('投资失败');
      }
   }).catch(err=>{
      //异常处理机制
      console.log(err);
   })
}

</script>

<style scoped>

</style>